"""
磁盘监控客户端
功能：采集磁盘分区数据并通过API提交到服务端
"""
import psutil
import requests
from datetime import datetime
from time import sleep

# 配置项
API_URL = "http://192.168.88.1:8000/v1/disk"  # 替换为实际服务端地址
TIMEOUT = 5  # 请求超时时间(秒)
UNITS = "MB"  # 数据单位(MB/GB)
EXCLUDE_FS = ['tmpfs', 'devtmpfs', 'squashfs']  # 排除的文件系统类型


def get_hostname():
    """获取主机名"""
    try:
        return psutil.users()[0].name if psutil.users() else "unknown"
    except:
        return "unknown"


def convert_units(bytes_value):
    """转换字节单位"""
    if UNITS == "MB":
        return round(bytes_value / (1024 * 1024), 2)
    elif UNITS == "GB":
        return round(bytes_value / (1024 * 1024 * 1024), 2)
    return bytes_value


def collect_disk_data():
    """采集磁盘分区数据"""
    hostname = get_hostname()
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    disks = []

    for partition in psutil.disk_partitions(all=False):
        if partition.fstype.lower() in EXCLUDE_FS:
            continue

        try:
            usage = psutil.disk_usage(partition.mountpoint)
            disks.append({
                "hostname": hostname,
                "date": current_time,
                "f_type": partition.fstype,
                "used": convert_units(usage.used),
                "free": convert_units(usage.free),
                "total": convert_units(usage.total),
                "used_percent": f"{usage.percent:.2f}%",
                "mountpoint": partition.mountpoint
            })
        except Exception as e:
            print(f"跳过分区 {partition.mountpoint}，采集错误: {str(e)}")

    return disks


def send_data():
    """发送数据到服务端"""
    for disk_data in collect_disk_data():  # 逐个分区发送
        try:
            response = requests.post(
                API_URL,
                json=disk_data,
                timeout=TIMEOUT
            )
            if response.status_code == 200:
                print(f"分区 {disk_data['mountpoint']} 数据提交成功")
            else:
                print(f"分区 {disk_data['mountpoint']} 提交失败，状态码：{response.status_code}")
        except requests.exceptions.RequestException as e:
            print(f"分区 {disk_data['mountpoint']} 请求失败：{str(e)}")


if __name__ == '__main__':
    send_data()
